// ==UserScript==
// @name     	NKE Geizhals inject skript.
// @include     http://geizhals.at/deutschland/?cat=nb15w*
// ==/UserScript==

var posNeg;
var concept;

// add the shutdown listener

// Add jQuery
(function() {
	if (typeof unsafeWindow.jQuery == 'undefined') {
		var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement,
		GM_JQ = document.createElement('script');

		GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
		GM_JQ.type = 'text/javascript';
		GM_JQ.async = true;

		GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
	}
	GM_wait();
})();
// Check if jQuery's loaded
function GM_wait() {
	if (typeof unsafeWindow.jQuery == 'undefined') {
		window.setTimeout(GM_wait, 100);
	} else {
		$ = unsafeWindow.jQuery.noConflict(true);
		injectNKE();

	}
}

//our NKE stuff
function injectNKE() {
	//load the variables
	var posNegString = GM_getValue("posNeg");
	var conceptString = GM_getValue("concept");
	if(posNegString == null) {
		posNeg = {
			"pos":[],
			"neg":[]
		}
	} else {
		posNeg = JSON.parse(posNegString);
	}

	if(conceptString != null) {
		concept = JSON.parse(conceptString);
	}

	//message field

	var msgDiv = $("#NKE_msg");
	if(msgDiv.length == 0) {
		$("<tr class='tr2' id='NKE_msg_row'><td  style='background-color:white' /> <td id='NKE_msg' colspan='3'  style='background-color:#FFFFCF;'><div id='#NKE_msg'><td id='NKE_conceptList' colspan='5'  style='background-color:#FFFFCF;'> </div></div> </td><td   style='background-color:white'><input type='reset' id='NKE_reset' value='reset'  /><input type='reset' id='NKE_debug' value='debug'  /></td></tr><tr><td>&nbsp;<td></tr>").insertBefore("#content_table_hdr");

		$("#NKE_reset").click( function() {
			reset();
			$('#NKE_msg_row').remove();
		});
		$("#NKE_debug").click(function(){
			alert(JSON.stringify(posNeg));
			
		});
	}

	if (concept) {
		displayConcept();
	} else {
		displayTop();
	}

	//exchange filter and list
	var filter = $("#gh_filterbox");
	filter.detach();
	$("#gh_content_wrapper").append(filter);

	//add the icons
	$("#content_table  tbody  tr:not(:first)").each( function() {

		$(this).find("td.chk  input").remove();

		var row = $(this);

		//remove the check box and add the images
		var addButtonPos = $("<div id='NKE_addpos'><img src='http://dl.dropbox.com/u/314254/plus.png' /></div>");
		var remButtonPos = $("<div id='NKE_rempos'><img src='http://dl.dropbox.com/u/314254/plus-active.png' /></div>");

		var uri = "http://geizhals.at/deutschland/" + row.find("td.ty a.ty").attr("href");
	
		var isSelected = false;

		$.each(posNeg, function(key,value) {
			if(value[0] == uri) {
				alert(uri);
				isSelected = true;
				return false;
			}
		});	
			
		
		if(!isSelected){
			remButtonPos.hide();
			addButtonPos.show();
		}else{
			remButtonPos.show();
			addButtonPos.hide();
		}
			
		var addButtonNeg = $("<div id='NKE_addneg'><img src='http://dl.dropbox.com/u/314254/minus.png' /></div>");
		var remButtonNeg = $("<div id='NKE_remneg'><img src='http://dl.dropbox.com/u/314254/minus-active.png' /></div>");
		remButtonNeg.hide();

		addButtonPos.click( function() {
			gatherData(true, row);

			addButtonPos.hide();
			remButtonPos.show();
			addButtonNeg.show();
			remButtonNeg.hide();
		});
		remButtonPos.click( function() {
			removeFromList(row);

			addButtonPos.show();
			remButtonPos.hide();
			addButtonNeg.show();
			remButtonNeg.hide();
		});
		addButtonNeg.click( function() {
			gatherData(false, row);

			addButtonPos.show();
			remButtonPos.hide();
			addButtonNeg.hide();
			remButtonNeg.show();
		});
		remButtonNeg.click( function() {
			removeFromList(row);

			addButtonPos.show();
			remButtonPos.hide();
			addButtonNeg.show();
			remButtonNeg.hide();
		});
		$(this).find("td.chk").append(addButtonPos);
		$(this).find("td.chk").append(remButtonPos);

		$(this).find("td.chk").append(addButtonNeg);
		$(this).find("td.chk").append(remButtonNeg);

	});
}

function gatherData(toAddList, tableRow) {
	//extract the data from the list page
	var uri  = "http://geizhals.at/deutschland/" +  tableRow.find("td.ty a.ty").attr("href");
	var name = tableRow.find("td.ty a.ty").text();

	//fetch data from details page
	$.get(uri, function(data) {
		var doc = $(data);
		var desc = $("#gh_proddesc",doc).text();
		addToList(toAddList,name,uri,desc);
	});
}

function addToList(toAddList, name, uri, desc) {
	//workaround for stupid GM_setValue Error

	GM_log("add to pos/neg List");

	var learnItemsMap;
	var otherItemsMap;
	if(toAddList) {
		learnItemsMap =  posNeg["pos"] ;
		otherItemsMap = posNeg["neg"];
	} else {
		learnItemsMap = posNeg["neg"];
		otherItemsMap =  posNeg["pos"] ;
	}

	learnItemsMap.push([uri,name,desc]);
	for(var i = 0; i<otherItemsMap.length;i++) {
		if(otherItemsMap[i][1]==uri) {
			otherItemsMap.splice(i,1);
		}
	}
	learn();

}

function removeFromList(uri) {
	//todo

}

function removeFromList(uri,list) {
	//todo
}

function learn() {

	gmAjax({
		method: "POST",
		url:"http://hanne.aksw.org:8082/interfaces/NKEGeizhals",
		data: "action=learn&data=" + JSON.stringify(posNeg),
		onload: function(response) {
			concept = JSON.parse(response.responseText);
			displayConcept();
			save();
		},
		headers: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		onerror: function(response) {
			alert("error: " + response.responseText);
		}
	});

}

function isOnPosList() {
	//todo
}

function isOnNegList() {
	//todo
}

function registerClick(data) {
	//register the click
	gmAjax({
		method: "POST",
		url: "http://hanne.aksw.org:8082/interfaces/NKEGeizhals",
		data: "action=feedback&data=" + encodeURIComponent( JSON.stringify(data)),
		headers: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		onerror: function(response) {
			alert("Error: "+ response.responseText);
		}
	});
}

function displayConcept() {

	var msgDiv = $("#NKE_msg");
	var conceptLink = $("<a id='NKE_show' href='"+concept["learned"]["link"]+"'>" +concept["learned"]["label"]+"</a> ");
	conceptLink.click( function() {
		registerClick(concept["learned"])
	});
	msgDiv.html(conceptLink);
	$("#NKE_conceptList").html("<div style=''bold;>Related Concepts</div>");
	if(concept["related"]) {
		$(concept["related"]).each( function(index,value) {
			var link  = $("<div> <a href='"+ value["link"]+"'>" +value["label"] +" ("+value["popularity"]+")"+"</a></div>");
			link.click( function() {
				registerClick(value);
			});
			$("#NKE_conceptList").append(link);

		});
	}

}

function displayTop() {
	$("#NKE_conceptList").append("<div style=''bold;>Top Concepts</div>");
	gmAjax({
		method: "GET",
		url: "http://hanne.aksw.org:8082/interfaces/NKEGeizhals?action=mostpopular",
		onload: function(response) {
			var result = JSON.parse(response.responseText);
			$.each(result["popular"], function(index,value) {

				var link  = $("<div> <a href='"+ value["link"]+"'>" +value["label"] +" ("+value["popularity"]+")"+"</a></div>");
				link.click( function() {
					registerClick(value);
				});
				$("#NKE_conceptList").append(link);
			});
		}
	});

}

function save() {

	window.setTimeout( function() {
		if(posNeg) {
			GM_setValue("posNeg",JSON.stringify(posNeg));
		}
		if (concept) {
			GM_setValue("concept",JSON.stringify(concept));
		};

		if(GM_getValue("posNeg") != JSON.stringify(posNeg)) {
			alert("save unsuccessfull");
		}

	},0);
}

function reset() {
	window.setTimeout( function() {
		concept = null;
		posNeg = {
			"pos":[],
			"neg":[]
		};
		GM_setValue("posNeg",JSON.stringify(posNeg ));
		GM_deleteValue("concept");
	},0);
}

var ajaxQueue = [];
var processAjaxQueue = function() {
	if (ajaxQueue.length > 0) {
		for (ajax in ajaxQueue) {
			var obj = ajaxQueue[ajax];
			// http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html
			GM_xmlhttpRequest(obj);
		}
		ajaxQueue = [];
	}
}
setInterval( function() {
	processAjaxQueue();
}, 100);
function gmAjax(obj) {
	ajaxQueue.push(obj);
}